package hr.fer.zpr.nmbp.project1.dao;

import com.db4o.ObjectContainer;
import com.db4o.constraints.UniqueFieldValueConstraintViolationException;

import hr.fer.zpr.nmbp.project1.dao.exceptions.PrimaryKeyConstraintException;
import hr.fer.zpr.nmbp.project1.model.Bolnica;
import hr.fer.zpr.nmbp.project1.model.Lijecnik;

import java.util.List;

public class BolnicaDAO {

	private ObjectContainer db;
	
	public BolnicaDAO(ObjectContainer db) {
		this.db = db;
	}
    
    public void save(Bolnica bolnica) {
    	
    	if(bolnica.getSifra() == null || bolnica.getSifra().isEmpty()) {
			throw new PrimaryKeyConstraintException("Šifra bolnice ne smije biti NULL");
		}
		
		this.db.store(bolnica);
		
		try{
			this.db.commit();
		}catch(UniqueFieldValueConstraintViolationException e){
			this.db.rollback();
			throw new PrimaryKeyConstraintException("Šifra bolnice već postoji u bazi podataka");
		}
    }
    
    public void delete(Bolnica bolnica) {
    	
    	List<Lijecnik> lijecnici = bolnica.getLijecnici();
    	
    	for(Lijecnik lijecnik : lijecnici){
    		if(lijecnik.getBolnica().equals(bolnica)){
    			lijecnik.setBolnica(null);
    		}
    	}
    	
    	db.delete(bolnica);
    	db.commit();
    }

    public List<Bolnica> load(Bolnica bolnicaPrototype) {    	
    	return db.queryByExample(bolnicaPrototype);
    }
    
    public List<Bolnica> loadAll() {    	
    	return db.query(Bolnica.class);
    }
    
}
